package org.springbus.ff.core;

import org.springbus.ff.util.BaseCommandOption;
import org.springbus.ff.util.CommandRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public class FFCommand {
    private List<String> inputCmds;
    private List<String> outputCmds;
    private List<String> optionsCmds;
    private  List<String> mapCmds;
    private List<String> filterCms;


    public FFCommand() {
        cmds = BaseCommandOption.getFFmpegBinary();
        inputCmds=new ArrayList<>();
        outputCmds=new ArrayList<>();
        optionsCmds=new ArrayList<>();
        mapCmds=new ArrayList<>();
        filterCms=new ArrayList<>();
    }

    private List<String>  cmds;

    public void setDuration(Float duration) {
        outputCmds.add("-t");
        outputCmds.add(String.valueOf(duration.floatValue()));
    }

    public void complexFilter(List<Object> filters, String map) {
        if(filters!=null && !filters.isEmpty()){
            filterCms.add("-filter_complex");
            StringBuilder sb=new StringBuilder("\"");
            StringJoiner joiner=new StringJoiner(";");
            for(Object o: filters){
              joiner.add(o.toString());
            }
            sb.append(joiner);
            sb.append("\"");
            filterCms.add(sb.toString());
        }
        if(map!=null && !map.isEmpty()){
            mapCmds.add("-map");
            mapCmds.add("\"["+map+"]\"");
        }
    }

    public void output(String filepath) {
       outputCmds.add(filepath);
    }

    public void outputOptions(List<String> options) {
        this.optionsCmds.addAll(options);
    }

    public void run() {
        cmds.addAll(inputCmds);
        cmds.addAll(filterCms);
        cmds.addAll(mapCmds);
        cmds.addAll(optionsCmds);
        cmds.addAll(outputCmds);

        log();
        CommandRunner.runProcess(cmds);
    }

    public void addInput(String file) {
        inputCmds.add("-i");
        inputCmds.add(file);
    }

    public void addColorInput(String color,String size) {
        //-f lavfi -i color=size=800x600:color=white,format=yuv420p
        inputCmds.add("-f");
        inputCmds.add("lavfi");
        inputCmds.add("color=size="+size+":color="+color+",format=yuv420p");
    }

    public void inputOptions(List<String> options) {
        this.inputCmds.addAll(options);
    }

    public void outputFPS(int fps) {
        outputCmds.add("-r");
        outputCmds.add(String.valueOf(fps));
    }
    private String log(){
        StringBuilder sb=new StringBuilder();
        for(String cmd:cmds) {
            sb.append(cmd+" ");
        }
        System.out.println("single cmd= "+ sb);
        return  sb.toString();
    }
}
